<template>
    <div class="Login_div" style="width: 100vw;height: 100vh">
        <div class="components_title">
                <div class="TitleTop_div" >
                    <a-row class="homework_title_row">
                        <a-col :span="24" class="homework_title_col" id="Login_title" >
                            巡线定位终端
                        </a-col>
                    </a-row>
                </div>

            <TitleMenu>
                <div slot="titleMenu_text" style="text-align: center">
                    <span>用户登录</span>
                </div>
            </TitleMenu>
        </div>
        <div class="Login_content" style="width: 100vw;height: calc(100vh - 30vw)" >
            <a-row class="Login_row_img">
                <a-col :span="24" >
                    <img src="./../assets/drawable-mdpi/icon_shield.png" width="127" height="112">
                </a-col>
            </a-row>
            <form  id="Login_form" name="Login_form"  element-loading-text="登陆服务器..." >
                <a-row class="Login_form_rows">
                    <a-col :span="9" class="Login_form_left" >
                        <el-select v-model="username" placeholder="用户名" class="login_user_select" @change="selectChange">
                            <el-option
                                    v-for="item in userInfo"
                                    :key="item.userName"
                                    :label="item.userName"
                                    :value="item.userName" class="login_user_option">
                            </el-option>
                        </el-select>
                    </a-col>
                    <a-col :span="15" class="Login_form_right"  >
                        <a-input id="Login_form_right1" class="Login_form_right_user" v-model.trim="username" placeholder="输入账号"/>
                    </a-col>
                </a-row>

                <a-row class="Login_form_rows">
                    <a-col :span="9" class="Login_form_left" >
                        任务密码<!--<span @click="$router.push('/test')"></span>-->
                    </a-col>
                    <a-col :span="15" class="Login_form_right"  >
                        <a-input id="Login_form_right2"  type="password"  class="Login_form_right_user" v-model.trim="password" placeholder="输入密码"/>
                    </a-col>
                </a-row>

                <a-row class="Login_form_rows" v-if="workModeList.length > 0">
                    <a-col :span="9" class="Login_form_left" >
                        <span @click="test">工作模式</span>
                    </a-col>
                    <a-col :span="15" class="Login_form_right"  >
                        <!--@change="getWorkModeSelected($event)"-->
                        <select  name="state" v-model="workModeSelected"
                         class="Login_form_right_user" id="Login_form_right_state">
                            <option :value="workMode.id"  :label="workMode.name"  v-for="workMode in workModeList">{{workMode.name}}</option>
                        </select>
                    </a-col>
                </a-row>

                <a-row class="Login_form_rows">
                    <a-col :span="9" class="Login_form_left">
                        任务编号<!--v-model.trim="planNo"-->
                    </a-col>
                    <a-col :span="15" class="Login_form_right">
                        <a-input class="Login_form_right_user" v-model="planNo" placeholder="输入后自动保存" ref="planNo" v-bind:onblur="handleOnInputs()"
                                 style="width: 60vw;padding: 0 0 0 2vw;" />

                    </a-col>
                </a-row>

                <a-row class="Login_form_rows1">
                    <a-col :span="24" class="imei_info" >
                        IMEI:{{gis4_imei | checkImei}}
                    </a-col>
                </a-row>

                <a-row class="Login_form_rows1">
                    <a-col :span="24" class="imei_info" >
                        版本号:{{currAppVersion}}
                    </a-col>
                </a-row>

                <a-row id="Login_btn_rows" >
                    <a-col :span="24" class="Login_btn_col" >
                        <a-button type="primary"  class="Login_btn" @click="loginSystem" clickMusic='true'>登录</a-button>
                    </a-col>
                </a-row>

                <div id="demo" v-if="this.onLine==='offline'">
                    <div id="demo1">
                        <div class="network_tip" id="network_tip"> ！网络开小差了，请退出刷新网络</div>
                    </div>
                </div>
            </form>
        </div>

        <div class="showBox" v-if="Loading" >
            <div class="progress_div" style="color: deepskyblue">最新版本更新中......</div>
            <div class="loading"></div>
        </div>

    </div>
</template>
<style>
    .network_tip{
        width: 100vw;
        height: 10vw;
        line-height: 10vw;
        color: darkorange;
        font-size: 4vw;
        margin-top: 4vw;
        generic-family:Microsoft Yahei;
    }
    .Login_form_right .ant-input:hover{
        border-color:white;
    }
    #Login_title{
       font-size: 5.5vw;
        generic-family: PingFangSC-Semibold;
        text-align: center;
    }
    .Login_div{
        width: 100vw;
        min-height:100%;
        margin: 0;
        padding: 0;
    }
    .components_title{
        width: 100vw;
        height: 30vw;
       text-align: center;
    }
    .Login_content{
        width: 100vw;
        margin: 0;
        padding: 0;
    }
    .Login_row_img{
        width: 100vw;
        height: 45vw;
        line-height: 45vw;
    }
    .Login_form_left{
        height: 14vw;
        line-height: 14vw;
        generic-family: PingFangSC-Regular;
        font-size:6vw;
        color: #000000;
        text-align: left;
        padding: 0 0 0 4vw;
    }
    .Login_form_right{
        height: 14vw;
        line-height: 14vw;
        padding: 0 4vw 0 0 ;
    }
    .Login_form_right_user{
        height: 12vw;
    }
    #Login_form_right1{
        width: 60vw;
        padding: 0 0 0 2vw
    }
    #Login_form_right2{
        width: 60vw;
        padding: 0 0 0 2vw
    }
    .Login_form_right .ant-input{
        font-size: 5vw;
        font-family: Microsoft Yahei;
        background-color: lightgray;
        border-radius: 2vw;
    }
    #Login_form_right_state{
        width: 60vw;
        background-color: lightgray;
        font-size: 5vw;
        border-radius: 2vw;
        border:0.3vw solid rgb(211, 211, 211);
        outline: none;
    }

    .Login_form_rows{
        height: 14vw;
        line-height: 14vw;
        generic-family: PingFangSC-Regular;
        font-size: 6vw;
        color: #000000;
    }
    .Login_btn_row{
        height: 15vw;
        line-height: 15vw;
        generic-family: PingFangSC-Regular;
        font-size: 6vw;
        color: #000000;
    }
    .Login_form_rows1{
        height: 8vw;
        line-height: 8vw;
        generic-family: PingFangSC-Regular;
        font-size: 6vw;
        color: #000000;
    }
    .imei_info{
        color: #00B7FF;
        height: 8vw;
        line-height: 8vw;
        font-size: 4vw;
        generic-family: PingFangSC-Regular;
    }
    .Login_btn_col{
        width: 100vw;
        height: 15vw;
        line-height: 15vw;
        padding: 0 4vw 0 4vw;
    }
    .Login_btn{
        width: 94.218vw;
        height: 14.68vw;
        line-height: 14.68vw;
        border-radius: 4vw;
        generic-family: PingFangSC-Semibold;
        font-size: 5.5vw;
        color: #FFFFFF;
        text-align: center;
        border: 0;
        background: linear-gradient(-180deg, #8F8F8F 0%, #5D5D5D 100%);
    }
    .login_user_select>.el-input>.el-input__inner{
        border-bottom: 0.5vw solid springgreen;
        height: 12vw;
        font-size: 5.5vw;
        font-family: "Microsoft Yahei", serif;
        text-align: center;
    }
    .login_user_option{
        font-size: 5vw;
        font-family: "Microsoft Yahei", serif;
    }
</style>
<script>
    import Vue from 'vue'
    import Ant from 'ant-design-vue'
    import 'ant-design-vue/dist/antd.css'
    import ElementUI from 'element-ui'
    import 'element-ui/lib/theme-chalk/index.css'
    import axios from 'axios'
    import TitleMenu from  './../components/TitleMenu'
    import {mapMutations} from 'vuex';
    import axiosHelper from '../axiosApi.js';
    import commonJs from '../js/commonJs.js';
    Vue.config.productionTip = false;
    Vue.use(Ant);
    Vue.use(ElementUI);
    export default {
        name: "Login",
        components:{TitleMenu},
        inject:['reload'],
        data() {
            return {
                username:'',
                password:'',
                phoneNumber:'',
                token:'',
                gis4_imei:"未获取",
                gis4_appVersion:0,
                last_appVersion:0,
                currAppVersion:'未获取',
                workModeSelected:"0",
                workModeSelectedId:'',
                workModeName : '',
                workModeList:[{
                    "id": "0",
                    "number": "0",
                    "name": "请选择",
                    "time": "0",
                    "stV_begin": "5",
                    "stV_end": "22",
                    "color": "FFFFFF",
                    "word": "",
                    "wordcolor": "FFFFFF"
                }],
                workModeId:'0',
                onLine: 'online',
                workOutId:'',//内存中得到的上次退出工作模式id
                //options: localStorage.getItem("historyUser")?JSON.parse(localStorage.getItem("historyUser")):[],
                Loading:false,
                userInfo:localStorage.getItem("userInfo")?JSON.parse(localStorage.getItem("userInfo")):[],
                planNo:'',//store变量的planNo最后是WorkPlanNo字段提交
                loginIntercomMsg:'',//登录对讲服务器消息
                intercomUserList:{},//获取对讲所有人员
                device:{
                    "available":true,
                    "platform":"Android",
                    "version":"",//8.1.0
                    "uuid":"c4a9210df92d3823",
                    "cordova":"",//8.0.0
                    "model":"",//RG725
                    "manufacturer":"RugGear",
                    "isVirtual":false,
                    "serial":"725CN18L03K00125",
                    "imeiId":"",//866719040003780
                    "phoneNumber":""
                },//设备信息
                apiHost:'',
                intercomHost:'',
                isImeiInit: false,
                isVersionInit: false,
                isInitOk: false,
                deviceReady:false,

            }
        },
        watch: {
            isImeiInit (newValue) {
                if(this.isInitOkabc()) {
                    this.isInitOk = true
                }
            },
            isVersionInit (newValue) {
                if(this.isInitOkabc()) {
                    this.isInitOk = true
                }
            },
            isInitOk (newValue) {
                if (newValue) {
                    this.sendInfo();
                }
            },
            deviceReady(newValue){
                if(newValue){
                    console.log("deviceReady",newValue);

                }
            }

        },
        created(){
            //created,mounted区别：
            //created:在模板渲染成html前调用，即通常初始化某些属性值，然后再渲染成视图。着重数据
            //mounted:在模板渲染成html后调用，通常是初始化页面完成后，再对html的dom节点进行一些需要的操作。着重方法

        },
        mounted(){
            /*if (this._isMobile()) {alert("手机端");} else {alert("pc端");}*/
            //添加内存中上次登录的用户信息
            if(this.userInfo.length>0){
                this.username = this.userInfo[0].userName;
                this.password = this.userInfo[0].passWord;
            }
            //如果没有这句代码，select中初始化会是空白的，默认选中就无法实现
            this.workModeSelected = this.workModeList[0].id;
            localStorage.removeItem("sid");
            this.$store.commit("updatePlanNo","");

            if(typeof cordova !== "undefined"){
                document.addEventListener("deviceready",this.myDeviceReady,false);
                this.autoLogin();//获取本地用户数据
            }else{
                this.getImei();//web端调试用,获取imei号，校验imei号，根据imei号得到apiHost和intercomHost
            }
            window.addEventListener("backbutton",this.eventBackButton,false);

            /*setTimeout(this.test(),2000);*/
        },
        computed: {
            /*currWorkMode() {
                return this.workModeList.find(t=> t.id === this.workModeSelected);
            },*/
        },
        methods: {
            myDeviceReady(){
                console.log('Device is Ready!');
                this.getImei();//获取imei号，校验imei号，根据imei号得到apiHost和intercomHost
                window.addEventListener('online',this.updateOnlineStatus,false);
                window.addEventListener('offline',this.updateOnlineStatus,false);
            },
            _isMobile() {
                //判断平台是否手机还是电脑
                let flag = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i)
                return flag;
            },
            isInitOkabc () {
                return this.isImeiInit && this.isVersionInit
            },
            updateOnlineStatus(){
                /*const {type} = e;
                this.onLine = type;
                console.log(this.onLine);
                if(this.onLine ==="online"){
                    this.getWorkMode()
                }*/
                let networkState = navigator.connection.type;
                console.log("网络产生变化:",networkState);
                console.log();
                /*if (networkState !== Connection.NONE) {*/
                if (networkState !== "none") {
                    this.onLine = "online";
                    let apiHost = localStorage.getItem("apiHost");
                    console.log("apiHost:",apiHost);
                    if(apiHost === null||apiHost === ""){
                        return
                    }else{
                        this.getWorkMode();
                    }
                }
                else {
                    this.onLine = "offline";
                }
            },
            ...mapMutations(['changeWorkModeId','changeWorkModeName']),
            loginSystem(){
                let me = this;
                //这里循环导致登录太慢了，需要后期优化
                //这里返回的是匹配到的JSON数组{}
                let mySelect = me.workModeList.find(t=> t.id === parseInt(me.workModeSelected));
                if(mySelect){
                    me.workModeName = mySelect.name;//得到工作模式名称，进行store变化和显示
                }
                if (me.username==='' || me.password==='') {
                    /*me.input_null_toast();*/
                    me.$toast("用户名/密码为空!!!","short","bottom",-40);
                }else if(me.workModeSelected === "0"||me.workModeSelected === 0){
                    me.selectFail();
                    setTimeout(me.refresh(),100);
                    return ;
                }
                else if(me.gis4_imei===""){
                    me.$toast("IMEI号刷新，请等待刷新重新登录","short","bottom",-40);
                    setTimeout(me.refresh(),1000);
                    return ;
                }
                else if(me.gis4_imei==="非法IMEI号，请更换机型"){
                    me.$toast("非法IMEI号，请更换机型","short","bottom",-40);
                    setTimeout(me.refresh(),1000);
                    return ;
                }
                else if(me.gis4_appVersion === 0){
                    console.log("me.gis4_appVersion:"+me.gis4_appVersion);
                    console.log("me.last_appVersion:"+me.last_appVersion);
                    me.$toast("版本号未刷新,请刷新重新登录","short","bottom",-40);
                    setTimeout(me.refresh(),1000);
                    return ;
                }
                else if(me.device.model!=="RG740"&&me.gis4_appVersion !== me.last_appVersion){
                    //版本号不是最新
                    me.$toast("版本号不是最新,请更新版本","short","bottom",-40);
                    me.checkVersion();
                    return;
                }
                else if(me.$store.state.apkConfig.location.isInstall === false){
                    //检测定位apk是否安装，安装了读取配置，检测应用，操作是否打开，转回页面，后台回传数据
                    let packageName = "io.cordova.hellocordova";
                    if(commonJs.isInstall(packageName)){

                    }

                }
                else {
                    me.$api.loginSyetem(me.username, me.password).then(response => {
                        let result = response.data.result;
                        if(response.data.status===200 ){
                            let tokenType = result.token_type;
                            let token=result.token;
                            let sid = result.sid;
                            let userToken=tokenType+" "+token;
                            let workModeId = me.workModeSelected;
                            console.log(workModeId);
                            /*let maxHistoryUserNumber = 9;//最多历史登录用户数量
                            console.log(me.userInfo);
                            if(maxHistoryUserNumber <= me.userInfo.length){
                                //超出最多历史登录用户数量
                                me.userInfo.splice(me.userInfo.length-1,1);
                            }*/
                            let uIndex = me.userInfo.findIndex(t => t.userName === me.username);//es6语法，找到符合的索引
                            if(uIndex>-1){
                                me.userInfo.splice(uIndex,1);//移除登录过的用户名
                            }
                            let currUserInfo = {sid:sid,userName:me.username,passWord:me.password};
                            me.userInfo.unshift(currUserInfo);//添加至历史用户数组
                            //localStorage.setItem("historyUser",JSON.stringify(historyUser));//历史用户数组以字符类型放进内存
                            me.$store.dispatch("updateUserInfo",me.userInfo);

                            /*me.addText();*/
                            localStorage.setItem("gis4_time",new Date().getTime().toString());//获取当前时间
                            localStorage.setItem("gis4_phone","18325042854");
                            /*let workModeName = this.currWorkMode.name;*/ //workname暂时拿不到
                            me.$store.commit('updateToken',userToken);
                            me.$store.commit('updateUsername',me.username);
                            me.$store.commit('updateSid',sid);
                            me.$store.commit("updatePlanNo",me.planNo);
                            me.changeWorkModeName(me.workModeName);
                            me.changeWorkModeId(workModeId);
                            /*me.updateToken({Authorization:me.userToken });
                            me.updateUsername({username: me.username});*/ //测试提交对象方法
                            /*提交选中的工作模式*/
                            me.$api.workModeSet(workModeId).then((resp)=>{
                                if(resp.data.status ===200){
                                    console.log("设置当前工作模式成功/login");
                                }else {
                                    console.log("设置当前工作模式失败返回其他状态码/login");
                                }

                            }).catch((error)=>{
                                console.log(error);
                            });

                            if(typeof cordova!=="undefined"){
                                me.addText(me.userInfo);//写入文件信息
                            }

                            //获取所有对讲用户 判断是否已经注册 选择登录或是注册登录 新版本不含基础apk对讲
                            /*try {
                                let pageIndex = 1;
                                let pageSize = 100000;//给个较大数字
                                me.$apiIntercom.getALLUsers(pageIndex,pageSize).then(result => {
                                    let data = result.data;
                                    if (data.code === 200) {
                                        me.intercomUserList = data.userlist;
                                       let index = me.intercomUserList.findIndex(t=>t.name === String(me.gis4_imei));
                                        if(index === -1){
                                            //属于新用户则进行注册
                                            me.registerIntercom();//在注册方法里进行登录
                                        }else{
                                            //已有用户则进行登录
                                            me.loginIntercom();
                                        }
                                    }else{
                                       return;
                                    }
                                }).catch(e =>{
                                    console.log("对讲服务器获取所有成员异常",e);
                                });
                            }catch (e) {
                                console.log("登陆对讲服务器异常",e);
                                me.$toast(me.loginIntercomMsg,"short","bottom",-100);//进行返回消息toast提示
                            }*/

                            //测试用路径 跳转到首页
                            /*me.showBottom();*/
                            me.$router.push('/homework');

                            //主动获取报警信息
                            me.$api.getFloodsWarning().then(function(response){
                                if(response.status === 200){
                                    let data = response.data.result.data;
                                    let temp = {};
                                    let end = [];
                                    if(data.length>0){
                                        if(typeof(navigator.notification)!=="undefined"){
                                            navigator.notification.beep(1);
                                        }
                                        for(let i = 0; i < data.length; i++){
                                            let a = data[i];
                                            if(!temp[a.workModeId]){
                                                end.push({
                                                    workModeId: a.workModeId,
                                                    workMode:a.workMode,
                                                    data: [a]
                                                });
                                                temp[a.workModeId] = a;

                                            }else{
                                                for(let j = 0; j < end.length; j++){
                                                    let b = end[j];
                                                    if(b.workModeId === a.workModeId){
                                                        b.data.push(a);
                                                        break;
                                                    }
                                                }
                                            }
                                        }//for end
                                    }
                                    me.$store.commit("countWarningNumber",data.length);
                                    me.$store.commit("updateFloodsWarning",end);

                                }
                            }).catch(function(error){
                                console.log(error);
                            });
                            //主动获取防洪信息
                            me.$api.getFloodsMessage().then(function(response){
                                if(response.status === 200){
                                    let data = response.data.result;
                                    console.log("FloodsMessage:",data);
                                    let message = {};
                                    for(let i in data){
                                        message["msg"+i] = data[i];
                                    }
                                    me.$store.commit("updateFloodsMessage",message);
                                }
                            }).catch(function(error){
                                console.log(error);
                            });
                            if(me.device.model!=="RG740"){
                                //发起百度定位请求 放后面即可，不管顺序
                                setTimeout(me.getBaiduLocaltion,2000);
                            }
                        }
                    }).catch((error) => {
                        console.log("网络：",me.onLine);
                        console.log("login error：",error);
                        //请求失败error.response.status
                        if(me.onLine ==="offline"){
                            me.networkFail_toast();
                        }else{
                            /*console.log(error.response.status);*/
                            if(error.status===401){
                                console.log("401用户名/密码错误");
                                me.login_fail();
                            }else{
                                console.log("请尝试退出重新登录");
                                me.reLogin();
                            }
                        }
                    })
                }
            },
            loginIntercom(){
                let me = this;
                let onConnSuccess = function(result){
                    console.log("login intercom result",result);
                    me.loginIntercomMsg = result;//进行返回消息toast提示
                    me.$toast(me.loginIntercomMsg,"short","bottom",-100);//进行返回消息toast提示
                    me.$store.commit("updateIsLoginServe",true);
                };
                let onConnError = function(error){
                    console.log(error);
                    me.loginIntercomMsg = error;//进行返回消息toast提示
                };
                let options = {
                    mUser:localStorage.getItem("gis4_imei"),
                    mPwd:"123456"
                };
                Intercom.initConn(onConnSuccess,onConnError,options);//登陆对讲服务器
            },
            registerIntercom(){
                let me = this;
                let name = me.gis4_imei;
                let passwd = "123456";
                let nick = me.username;
                me.$apiIntercom.addUser(name,passwd,nick).then(result => {
                    let data = result.data;
                    if (data.code === 200) {
                        me.$toast("注册对讲服务器成功","short","bottom",-100);
                        //注册成功进行登录
                        me.loginIntercom();

                    } else{
                        me.$toast("注册对讲服务器失败","short","bottom",-100);
                        return;
                    }
                }).catch(e =>{
                    me.$toast("注册对讲服务器失败","short","bottom",-100);
                    console.log(e);
                });

            },
            updateUserNick(){
              //修改当前用户userNick
                let onSuccess = function(result){
                    console.log("修改当前用户名成功",result);
                };
                let onError = function(error){
                    console.log(error);
                };
                let options = {
                    newName:localStorage.getItem("username"),
                };
                Intercom.updateUserNick(onSuccess,onError,options);//登陆对讲服务器
            },
            showBottom : function() {
                let self = this;
                if(window.plugins.toast){
                    window.plugins.toast.showWithOptions({
                            message: "登陆成功",
                            duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                            position: "bottom",
                            addPixelsY: -60  // added a negative value to move it up a bit (default 0)
                        },
                        // implement the success callback
                        function (result) {
                            console.log('toast success: ');
                            if (result && result.event) {
                                console.log('toast success1: ');
                                self.$router.push('/homework');
                            } else {
                                console.log("toast error: ");
                            }
                        });
                }else {
                    self.$router.push('/homework');
                }

            },
            input_null_toast :function () {
                //待封装this.$msg.showToast({})
                    window.plugins.toast.showWithOptions(
                        {
                            message: "用户名/密码为空",
                            duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                            position: "bottom",
                            addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                        },
                        function(){console.log('toast success: ')},
                        function(){console.log('toast error: ')}
                    );
            },
            networkFail_toast :function () {
                window.plugins.toast.showWithOptions(
                    {
                        message: "请检查设备网络环境",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('toast success: ')},
                    function(){console.log('toast error: ')}
                );
            },
            reLogin(){
                window.plugins.toast.showWithOptions(
                    {
                        message: "请尝试退出重登",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('toast success: ')},
                    function(){console.log('toast error: ')}
                );
            },
            networkFail() {
                window.plugins.toast.showWithOptions(
                    {
                        message: "请检查网络连接",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('toast success: ')},
                    function(){console.log('toast error: ')}
                );
            },
            login_fail :function () {
                window.plugins.toast.showWithOptions(
                    {
                        message: "用户名/密码错误",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    function(){console.log('login toast success: ')},
                    function(){console.log('login toast error: ')}
                );
            },
            selectFail : function() {
                window.plugins.toast.showWithOptions({
                        message: "未选择工作模式",
                        duration: "short", // which is 2000 ms. "long" is 4000. Or specify the nr of ms yourself.
                        position: "bottom",
                        addPixelsY: -40  // added a negative value to move it up a bit (default 0)
                    },
                    // implement the success callback
                    function(){console.log('toast success: ')},
                    function(){console.log("下拉框初始化Toast失败")}
                    );

            },
            getWorkMode(){
                let me = this;
                console.log("初始化工作模式...");
                me.$api.getWorkMode().then( resp =>{
                    let result = resp.data.result.data;
                    /*console.log(result);*/
                    //状态码200
                    if(resp.status === 200){
                        me.workModeList= me.workModeList.concat(result);
                        me.workOutId = localStorage.getItem('workModeId');
                        if(me.workOutId>0){
                            me.workModeSelected = me.workOutId;
                        }else{
                            me.workModeSelected = 0;
                        }
                       let lineWorkMode = me.workModeList.filter((item)=>item.name==="线路作业");//保存线路作业的id，方便提交线路模式id
                       let floodWorkMode = me.workModeList.filter((item)=>item.name==="防洪巡查");//保存线路作业的id，方便提交线路模式id
                       localStorage.setItem("lineWorkModeId",lineWorkMode[0].id);
                       localStorage.setItem("floodWorkModeId",floodWorkMode[0].id);
                       console.log("工作模式初始化完成...");
                    }
                }).catch(error =>{
                    //请求失败
                    console.log("init workMode failed:"+error);

                })
            },
            getWorkModeSelected($event){
               /* let workModeId = this.currWorkMode.id;
                let workModeName = this.currWorkMode.name;
                console.log(workModeId+workModeName);*/
            },
            getImei(){
                let me = this;
                console.log("初始化imei");
                me.$store.commit("updateApiHost","");
                me.$store.commit("updateIntercomHost","");
                if(typeof (cordova)==="undefined"){
                    //web调试用
                    me.gis4_imei = "866719040003400"; //web调试用,测试完毕删除 866719048888888|866719040003400
                    me.$store.commit("updateImei",me.gis4_imei);
                    //测试用
                    axios.get("http://www.tdzcsoft.com:7007/api/config",
                        {headers:
                            {
                                gis4_imei:me.gis4_imei
                            }
                        }).then(result=>{
                        console.log("Web端初始化Host成功");
                        let data = result.data;
                        me.apiHost = data.api.serverAddress+":"+data.api.serverPort;
                        me.intercomHost = data.intercom.serverAddress+":"+data.intercom.serverPort;
                        console.log("apiHost:",me.apiHost,"intercomHost",me.intercomHost);
                        me.$store.commit("updateApiHost",me.apiHost);
                        me.$store.commit("updateIntercomHost",me.intercomHost);//web调试用
                        axiosHelper.update(me.apiHost);
                        me.isImeiInit=true;
                        me.getWorkMode();//获取工作模式
                        me.getMyVersion();//获取到版本号后发送开机信息，针对G01A不升级
                    }).catch(e => {
                        console.log(e);
                    });
                }else{
                    //手机端用
                    me.gis4_imei = device.imeiId;//device.imeiId
                    me.$store.commit("updateImei",me.gis4_imei);
                    let phoneModel = device.model;
                    localStorage.setItem("phoneModel",phoneModel);
                    me.device = device;
                    axios.get("http://www.tdzcsoft.com:7007/api/config",
                        {headers:
                            {
                               gis4_imei:me.gis4_imei
                            }
                        }).then(result=>{
                            console.log("手机端初始化Host成功");
                            let data = result.data;
                            me.apiHost = data.api.serverAddress+":"+data.api.serverPort;
                            let intercomHost = data.intercom.serverAddress+":"+data.intercom.serverPort;
                            me.$store.commit("updateApiHost",me.apiHost);
                            me.$store.commit("updateIntercomHost",intercomHost);
                            axiosHelper.update(me.apiHost);
                            me.isImeiInit=true;
                            me.getWorkMode();//获取工作模式
                            me.getMyVersion();//获取到版本号后发送开机信息，针对G01A不升级
                    }).catch(e => {
                        console.log(e);
                    });

                }
            },
            getMyVersion(){
                let me = this;
                console.log("初始化软件版本");
                // 获取当前移动设备已经安装的版本
                if(typeof (cordova)!=="undefined"){
                    cordova.getAppVersion.getVersionNumber().then( version => {
                        me.currAppVersion = version;
                        me.gis4_appVersion = parseInt(me.currAppVersion.toString().replace(/\./g,''));
                        me.$store.commit('updateAppVersion',me.gis4_appVersion);
                        me.isVersionInit=true;
                        // 1.获取当前版本号
                        // 2.获取服务器端的最新版本的数据源
                        // 3.进行版本比较,如果当前的版本号与服务器的版本号不一致时,下载并安装最新的应用程序安装包
                        if(me.device.model!=="RG740"){
                            me.checkVersion();//针对G01A不升级
                        }

                    }).catch( error => {
                        console.log("js插件获取app系统版本失败"+error);
                    });
                }else{
                    me.device.model = "web";
                    me.currAppVersion = "1.09.21.1716";
                    me.gis4_appVersion = "109211716";
                    me.last_appVersion= "109211716";
                    me.$store.commit('updateAppVersion',me.gis4_appVersion);
                    me.isVersionInit=true;
                }

            },
            sendInfo(){
                let me = this;
                //发送开机信息
                let phoneNumber = me.device.phoneNumber;
                if(phoneNumber === ""||typeof phoneNumber ==="undefined"){
                    me.phoneNumber = "18325042856"
                }else{
                    console.log("aaa");
                    let temp = phoneNumber.replace('+86', '');
                    let reg = /^[0-9]*$/;
                    if (reg.test(temp)) {
                        me.phoneNumber = temp;
                    }else{
                        me.phoneNumber = "18325042855";
                    }
                }
                let param = {
                    version:me.currAppVersion,
                    model:me.device.model,
                    appVersion:me.device.version,
                };
                let config = {
                    "headers":{
                        "Content-Type":"application/json",
                        "gis4_phone":me.phoneNumber,
                        "gis4_imei":me.gis4_imei,
                    }
                };
                axios.post('http://'+me.apiHost+'/app/device/start',param, config).then(result=>{
                    if(result.status===200){
                        console.log("开机信息发送成功");
                    }
                }).catch(error=>{
                    console.log("开机信息异常"+error);
                });
            },

            //无网环境文字右到左滚动提示效果
            scrollTip(){
                let demo = document.getElementById("demo");
                let demo1 = document.getElementById("demo1");
                let demo2 = document.getElementById("demo2");
                demo2.innerHTML = document.getElementById("demo1").innerHTML;
                function Marquee() {
                    if (demo.scrollLeft - demo2.offsetWidth >= 0) {
                        demo.scrollLeft -= demo1.offsetWidth;
                    }
                    else {
                        demo.scrollLeft++;
                    }
                }
                let myvar = setInterval(Marquee,20);//30默认值，数值越小越快
                demo.onmouseout = function () {
                    myvar = setInterval(Marquee, 20);
                   };
                demo.onmouseover = function () {
                    clearInterval(myvar);
                };
            },
            selectChange(userName){
                let me = this;
                let object = me.userInfo.find( t => t.userName === userName);
                me.password = object.passWord;//同步密码
            },
            getBaiduLocaltion(){
                let me = this;
                me.$getBaiduLocation().then(result => {
                    console.log("init getLocation result",result);
                }).catch(error => {
                    //me.$store.commit('hideLoading');
                    console.log("getCooUsingBaiduSdk error:",error);
                    me.$alert("定位信息未及时获取");
                });
            },
            refresh(){
                let me = this;
                setTimeout(function() {
                    me.reload();
                },500);
            },
            update(lastVersionStringPoint){
                let me = this;
                console.log("更新下载中......");
                let fileTransfer = new window.FileTransfer();
                let joinUrl = "http://files.gis4.tdzcsoft.com/files/apk/" + lastVersionStringPoint+ ".apk";//与服务器app文件名和接口列表版本一致

                let uri = encodeURI(joinUrl);//'http://files.gis4.tdzcsoft.com/files/apk/patrol_V1.05.21.apk'
                //let fileURL = 'cdvfile://localhost/temporary/patrol_V1.05.21.apk';
                let fileURL = 'cdvfile://localhost/persistent/patrol/file/'+ lastVersionStringPoint + '.apk';

                fileTransfer.download(
                    uri, fileURL, function (entry) {
                        me.Loading = false;
                        console.log('更新下载完成: ');
                        console.log(entry.toURL());
                        cordova.plugins.fileOpener2.open(
                            fileURL,
                            'application/vnd.android.package-archive'
                        );

                    },
                    function (error) {
                        console.log('下载更新版本出错:');
                        console.log(error);
                        console.log(error.source );
                        console.log(error.target );
                        console.log(error.code );
                        me.Loading = false;
                    },
                    false, {
                        headers: {
                            'Authorization': 'Basic dGVzdHVzZXJuYW1lOnRlc3RwYXNzd29yZA=='
                        }
                    }
                )

            },
            checkVersion(){
                let me = this;
                me.$api.getVersion().then( resp => {
                    let result = resp.data.result;
                    //状态码200，"data": ["1.07.16.1015","1.07.16.1020"] 这里如果版本回溯，可服务器端将历史版本加在最后即可，然后更新服务器的apk
                    if(resp.status === 200){
                        me.checkVersions = result;
                        console.log(me.checkVersions);
                        for(let i = 0;i<me.checkVersions.length;i++){
                            let splitArray = me.checkVersions[i].version.split(".");
                            let intString = splitArray.join("");
                            me.checkVersions[i].sortVersion = parseInt(intString);
                        }
                        me.checkVersions.sort(function (a, b) {
                            return (a.sortVersion - b.sortVersion)
                        });
                        let myVersionString = localStorage.getItem("gis4_appVersion");//当前安装app的版本号
                        let myVersion = parseInt(myVersionString);//当前安装app的版本号
                        let lastVersionStringPoint = me.checkVersions[(me.checkVersions.length-1)].version;//得到最后最新的版本号String类型,如1.07.16.1020

                        me.last_appVersion = me.checkVersions[(me.checkVersions.length-1)].sortVersion;//得到最后最新的版本号Int类型,如107161020
                        console.log("当前版本:" + myVersion + ",系统最新版本:" + me.last_appVersion);
                        if(me.last_appVersion !== myVersion){
                            //下方可以出现一个更新按钮或者弹窗
                            let message = "最新版本:V"+lastVersionStringPoint+" 请安装新版本后使用,如遇到安装未知软件来源，请设置允许即可";
                            let title = "版本更新";
                            let buttonLabels = ["确认",""];//出现界面：2取消 1确认

                            if(typeof(navigator)==='undefined' || typeof(navigator.notification)==='undefined' || typeof(navigator.notification.confirm)==='undefined') {
                                console.log(message);
                                return;
                            }
                            navigator.notification.confirm(message, confirmCallback, title, buttonLabels);
                            function confirmCallback(buttonIndex) {
                                console.log(buttonIndex);
                                if(buttonIndex===1){
                                    me.Loading=true;
                                    me.update(lastVersionStringPoint);
                                }
                                else{me.checkVersion();}
                            }
                        }
                    }
                }).catch( error =>{
                    //请求失败
                    console.log("init version failed:"+error);
                });
            },
            autoLogin(){
                //获取本地用户数据，有则忽略文本读取，无则读取文本数据给本地存储。每次登录将本地存储覆盖到文本信息
                let me = this;
                let userInfo = localStorage.getItem("userInfo");
                if(userInfo===null||typeof (userInfo)==="undefined"||userInfo===""){
                    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
                        console.log('打开的文件系统: ' + fs.name);
                        fs.root.getDirectory('patrol', {create: false}, function (dirEntry) {
                            dirEntry.getDirectory('assets', {create: false}, function (subDirEntry) {
                                subDirEntry.getFile("name.text", {create: false, exclusive: false}, function (fileEntry) {
                                    //console.log("是否是个文件？" + fileEntry.isFile.toString());
                                    fileEntry.name == 'name.text';
                                    fileEntry.fullPath == 'patrol/assets/name.text';
                                    readFile(fileEntry);
                                }, onErrorCreateFile);
                            }, onErrorGetDir);
                        }, onErrorGetDir);
                    }, onErrorLoadFs);
                }

                //读取文件
                function readFile(fileEntry) {
                    fileEntry.file(function (file) {
                        let reader = new FileReader();
                        reader.onloadend = function () {
                            /*console.log("file read success:" + this.result);*/
                            me.userInfo =JSON.parse(this.result);
                            if(me.userInfo.length>0){
                                me.username = me.userInfo[0].userName;
                                me.password = me.userInfo[0].passWord;
                            }
                        };
                        reader.readAsText(file);
                    }, onErrorReadFile);
                }

                //FileSystem加载失败回调
                function onErrorLoadFs(error) {
                    console.log("文件系统加载失败！"+error)
                }

                //文件夹创建失败回调
                function onErrorGetDir(error) {
                    console.log("文件夹创建失败！"+error)
                }

                //文件创建失败回调
                function onErrorCreateFile(error) {
                    console.log("文件创建失败！"+error)
                }

                //读取文件失败响应
                function onErrorReadFile() {
                    console.log("文件读取失败!"+error);
                }
            },
            addText(userInfo){
                //创建并写入文件
                /*
                 * 打开或创建文件夹,创建文件并写入内容
                 * Android:sdcard/xbrother/assets目录
                 * IOS:cdvfile://localhost/persistent/xbrother/assets目录
                 * 文件目录存在则打开,不存在则创建
                 * */
                let tasksStr = JSON.stringify(userInfo);
                window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
                    console.log('打开的文件系统: ' + fs.name);
                    fs.root.getDirectory('patrol', {create: true}, function (dirEntry) {
                        dirEntry.getDirectory('assets', {create: true}, function (subDirEntry) {
                            subDirEntry.getFile("name.text", {create: true, exclusive: false}, function (fileEntry) {
                                fileEntry.name == 'name.text';
                                fileEntry.fullPath == 'patrol/assets/name.text';
                                //文件内容
                                let dataObj = new Blob([tasksStr], {type: 'text/plain'});
                                //写入文件
                                writeFile(fileEntry, dataObj);
                            }, onErrorCreateFile);
                        }, onErrorGetDir);
                    }, onErrorGetDir);
                }, onErrorLoadFs);

                //将内容数据写入到文件中
                function writeFile(fileEntry, dataObj) {
                    //创建一个写入对象
                    fileEntry.createWriter(function (fileWriter) {
                        //文件写入成功
                        fileWriter.onwriteend = function () {
                            console.log("Successful file write...");
                        };
                        //文件写入失败
                        fileWriter.onerror = function (e) {
                            console.log("Failed file write: " + e.toString());
                        };
                        //写入文件
                        fileWriter.write(dataObj);
                    });
                }

                //FileSystem加载失败回调
                function onErrorLoadFs(error) {
                    console.log("文件系统加载失败！"+error)
                }

                //文件夹创建失败回调
                function onErrorGetDir(error) {
                    console.log("文件夹创建失败！"+error)
                }

                //文件创建失败回调
                function onErrorCreateFile(error) {
                    console.log("文件创建失败！"+error)
                }
            },
            handleOnInputs(){
                let me = this;
                if(me.planNo!==''){
                    let reg = /^[0-9a-zA-Z]+$/;
                    if(!reg.test(me.planNo)) {
                        me.$toast("只能输入字母或数字","short","top",40);
                        me.planNo = '';
                    }
                }
            },
            test() {
                //检测平台
                let u = navigator.userAgent;
                let ua = navigator.userAgent.toLowerCase();
                console.log("navigator.userAgent u:"+u);
                console.log("navigator.userAgent ua:"+ua);
                if(!!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)){//如果是ios
                    //do something
                    console.log("ios");
                }
                if (ua.match(/android/i) == "android") {//如果是android
                    // do something
                    console.log("android");
                }

                //测试检测apk安装和打开
                /* params and extras */
                let sApp = startApp.set({
                    /*"action":"ACTION_MAIN",
                    "category":"CATEGORY_DEFAULT",
                    "type":"text/css",
                    "package":"io.cordova.hellocordova",//包名owt.sample.conference
                    "uri":"file://data/index.html",
                    "flags":["FLAG_ACTIVITY_CLEAR_TOP","FLAG_ACTIVITY_CLEAR_TASK"],
                    //"component": ["io.cordova.hellocordova","io.cordova.hellocordova.Activity"],
                    "intentstart":"startActivity",*/
                    "flags": ["FLAG_ACTIVITY_NEW_TASK"],
                    "component": ["io.cordova.hellocordova","io.cordova.hellocordova.MainActivity"]
                }, {
                    "userName":"1001",
                    "passWord":"123456"
                });

                let sApp1 = startApp.set({
                    "package":"owt.sample.conference"
                });
                sApp.check(function(values) { /* success */
                    console.log("check OK");
                    console.log(values);
                }, function(error) { /* fail */
                    console.log("check error"+error);
                });

                sApp1.check(function(values) { /* success */
                    console.log("check1 OK");
                    console.log(values);
                }, function(error) { /* fail */
                    console.log("check error"+error);
                });

                sApp.start(function() { /* success */
                    console.log("start OK");
                }, function(error) { /* fail */
                    console.log("start error"+error);
                });

            }
        },
        beforeDestroy(){
            window.removeEventListener('online',this.updateOnlineStatus);
            window.removeEventListener('offline', this.updateOnlineStatus);

        },
        filters: {
            checkImei(value) {
                let reg = /^[0-9]*$/;
                if (!reg.test(value)) {
                    value = "非法IMEI号，请更换机型";
                }
                return value;
            },
        }
    }

</script>

